package Client.GUI;

import Client.Net.*;
import Library.Events.ValueEvent;
import Library.Game.*;
import Library.IDisposable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.rmi.RemoteException;
import java.util.*;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;

/**
 *
 */
public class pnlLobby extends javax.swing.JPanel implements IDisposable
{
    protected transient ICommunication m_Communication;
    protected transient boolean m_IsHost;
    /**
     * Creates new form pnlLobby
     * @param communication communication naar de service
     * @param isHost vlag die aangeeft of deze game gehost is of gejoined
     */
    public pnlLobby(ICommunication communication, boolean isHost)
    {
        initComponents();
        btnStart.setVisible(isHost);
        m_Communication = communication;
        m_IsHost = isHost;
	register();
        try
        {
            rebuildPlayerList();
        }
        catch (RemoteException ex)
        {
            ex.printStackTrace();
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
    }
    
    protected void register()
    {
	m_Communication.getService().onPlayerJoined.register(onPlayerJoined);
	m_Communication.getService().onPlayerLeft.register(onPlayerLeft);
	m_Communication.getService().onGameStatusChanged.register(onGameStatusChanged);
    }
    
    protected void unregister()
    {
	m_Communication.getService().onPlayerJoined.unregister(onPlayerJoined);
	m_Communication.getService().onPlayerLeft.unregister(onPlayerLeft);
	m_Communication.getService().onGameStatusChanged.unregister(onGameStatusChanged);
    }
    
    protected ActionListener onGameStatusChanged = new ActionListener()
    {
	public void actionPerformed(ActionEvent e)
	{
	    try
	    {
		ValueEvent<Integer> ev = (ValueEvent<Integer>)e;
		int status = ev.getValue().intValue();
		if (status == GameState.GAME_PREPARING)
		{
		    pnlClientWorldMap pnl = new pnlClientWorldMap(m_Communication);
		    m_Communication.SetContent(pnl);
		}
	    }
	    catch (Exception ex)
	    {
		ex.printStackTrace();
	    }
	}
    };
    
    protected ActionListener onPlayerJoined = new ActionListener()
    {
	public void actionPerformed(ActionEvent e)
	{
	    try
	    {
		//ValueEvent<IPlayer> ev = (ValueEvent<IPlayer>)e;
		rebuildPlayerList();
	    }
	    catch (Exception ex)
	    {
		ex.printStackTrace();
	    }
	}
    };
    
    protected ActionListener onPlayerLeft = new ActionListener()
    {
	public void actionPerformed(ActionEvent e)
	{
	    try
	    {
		//ValueEvent<IPlayer> ev = (ValueEvent<IPlayer>)e;
		rebuildPlayerList();
	    }
	    catch (Exception ex)
	    {
		ex.printStackTrace();
	    }
	}
    };
    
    protected void rebuildPlayerList() throws RemoteException, Exception
    {
        IGameInfo info = m_Communication.getService().getGame();
        lblGameName.setText("Gamename: " + info.getName());
	lblPlayers.setText("Players: " + info.getPlayers() + "/" + info.getMaxPlayers());
	lblGameTime.setText("GameTime: " + info.getGameTime());
	lblTurnTime.setText("TurnTime: " + info.getTurnTime());
	
	DefaultListModel mdl = (DefaultListModel)lstPlayers.getModel();
        mdl.clear();
        Iterator<IPlayer> it = info.getPlayerList().iterator();
        while (it.hasNext())
        {
           mdl.addElement(it.next().getName());
        }

        // Controleer of startknop moeten worden enabled
        if (m_IsHost)
           btnStart.setEnabled(info.getPlayerList().size() > 1);
    }

    public void startGame()
    {
        try
	{
	    if (!m_Communication.getService().startGame())
		JOptionPane.showMessageDialog(this, "Cannot start game!");
	    else
                btnStart.setVisible(false);
        }
	catch (RemoteException ex)
	{
	    ex.printStackTrace();
	    JOptionPane.showMessageDialog(this, "Cannot start game!");
	}
	catch (Exception ex)
	{
	    ex.printStackTrace();
	    JOptionPane.showMessageDialog(this, "Cannot start game!");
	}
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        lblGameName = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        btnStart = new javax.swing.JButton();
        btnLeave = new javax.swing.JButton();
        lblPlayers = new javax.swing.JLabel();
        lblGameTime = new javax.swing.JLabel();
        lblTurnTime = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        lstPlayers = new javax.swing.JList();

        setMinimumSize(new java.awt.Dimension(500, 380));
        setPreferredSize(new java.awt.Dimension(500, 380));
        setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        lblGameName.setText("<GameName>");
        jPanel1.add(lblGameName, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 7, -1, -1));

        jLabel1.setText("Connected players:");
        jPanel1.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 67, -1, -1));

        btnStart.setText("Start");
        btnStart.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnStartActionPerformed(evt);
            }
        });
        jPanel1.add(btnStart, new org.netbeans.lib.awtextra.AbsoluteConstraints(393, 256, -1, -1));

        btnLeave.setText("Leave");
        btnLeave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLeaveActionPerformed(evt);
            }
        });
        jPanel1.add(btnLeave, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 256, -1, -1));

        lblPlayers.setText("<Players>");
        jPanel1.add(lblPlayers, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 27, -1, -1));

        lblGameTime.setText("<GameTime>");
        jPanel1.add(lblGameTime, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 47, -1, -1));

        lblTurnTime.setText("<TurnTime>");
        jPanel1.add(lblTurnTime, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 47, -1, -1));

        lstPlayers.setModel(new javax.swing.DefaultListModel());
        jScrollPane2.setViewportView(lstPlayers);

        jPanel1.add(jScrollPane2, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 87, 440, 163));

        add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 500, 380));
    }// </editor-fold>//GEN-END:initComponents

    private void btnStartActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnStartActionPerformed
        startGame();        
    }//GEN-LAST:event_btnStartActionPerformed

    private void btnLeaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLeaveActionPerformed
        try
        {
            m_Communication.getService().leaveGame();
	    unregister();
        }
        catch (RemoteException ex)
        {
            ex.printStackTrace();            
        }
        catch (Exception ex)
        {
            ex.printStackTrace();            
        }
        // Go back to GameList
        m_Communication.SetContent(new pnlGameList(m_Communication));
    }//GEN-LAST:event_btnLeaveActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnLeave;
    private javax.swing.JButton btnStart;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel lblGameName;
    private javax.swing.JLabel lblGameTime;
    private javax.swing.JLabel lblPlayers;
    private javax.swing.JLabel lblTurnTime;
    private javax.swing.JList lstPlayers;
    // End of variables declaration//GEN-END:variables

    public void dispose()
    {
	unregister();
    }
}
